import SwiftUI
import MapKit

struct MapView: View {
    @StateObject private var locationManager = LocationManager()
    @Environment(\.presentationMode) var presentationMode
    @State private var region = MKCoordinateRegion(
        center: CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194),
        span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
    )
    
    var body: some View {
        NavigationView {
            ZStack {
                MainView()
                VStack {
                    Back(title: "Location", onBackTap: {
                        self.presentationMode.wrappedValue.dismiss()
                    }, onImageTap: {})
                    VStack {
                        if let userLocation = locationManager.userLocation {
                            Map(coordinateRegion: $region, showsUserLocation: true)
                                .onAppear {
                                    DispatchQueue.main.async {
                                        region.center = userLocation.coordinate
                                    }
                                }
                                .edgesIgnoringSafeArea(.all)
                           
                            VStack(alignment:.leading) {
                                Text(" latitude: \(userLocation.coordinate.latitude)")
                                    .foregroundColor(.white)
                                Text(" longitude: \(userLocation.coordinate.longitude)")
                                    .foregroundColor(.white)
                               
                            }
                            .padding()
                        } else {
                            Text("positioning...")
                                .padding()
                        }
                    }
                }
            } .navigationBarHidden(true)
                .navigationBarBackButtonHidden(true)
                .navigationViewStyle(StackNavigationViewStyle())
        } .navigationBarHidden(true)
            .navigationBarBackButtonHidden(true)
            .navigationViewStyle(StackNavigationViewStyle())
    }
}
#Preview{
    MapView()
}
